﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Qu.SeniorProject.Model;
using System.Text.RegularExpressions;

namespace Qu.SeniorProject.WebUI.Controllers
{
    public class GradingController : Controller
    {
        private UserInfo GetUserInfo()
        {
            UserInfo userInfo = Session["UserInfo"] as UserInfo;
            if (Request.IsAuthenticated && userInfo == null)
            {
                //Store the User Info in a Session
                userInfo = UserRepository.GetUserInfo(User.Identity.Name);

                if (userInfo != null)
                    Session["UserInfo"] = userInfo;
            }
            return userInfo;
        }

        [HttpGet]
        [Authorize]
        public ActionResult Grading(int projectID, string gradingType)
        {
            //int projectID = 0;
            //if (TempData["projectID"] != null)
            //    projectID = (int)TempData["projectID"];
            //else
            //    projectID = (int)Request.Form["projectID"];

            UserInfo userInfo = Session["UserInfo"] as UserInfo;
            if (userInfo == null)
                return RedirectToAction("LogOn", "Account");

            int facultyID = int.Parse(userInfo.UserID);

            ProjectEvaluation projectEvaluation = GradingRepository.GetProjectEvaluation(projectID, facultyID, gradingType);

            int evaluationID = 0;
            if (projectEvaluation != null)
            {
                ViewBag.EvaluationID = projectEvaluation.EvaluationID;
                ViewBag.OverallComment = projectEvaluation.Comments;
                evaluationID = projectEvaluation.EvaluationID;
            }

            List<EvaluationDetail> evaluationDetails = GradingRepository.GetProjectEvalautionDetails(projectID, facultyID, evaluationID, gradingType);

            foreach (var evaluationDetail in evaluationDetails)
                evaluationDetail.Description = Regex.Replace(evaluationDetail.Description, @"\r\n", "<br/>", RegexOptions.Multiline);

            ProjectSummary projectSummary = ProjectRepository.GetProjectSummary(projectID, facultyID);

            ViewBag.GradingType = gradingType;
            ViewBag.ProjectSummary = projectSummary;
            ViewBag.Ratings = GradingRepository.GetRatings(true);
            ViewBag.RatingsForCourseAssessment = GradingRepository.GetRatings(false);

            ViewBag.ProjectID = projectID;
            ViewBag.UserInfo = userInfo;
            return View(evaluationDetails);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Grading(int? evaluationID, string gradingType, int projectID, int facultyID, string overallComment, FormCollection formCollection)
        {
            var evaluationsDetails = new List<ProjectEvaluationDetail>();
            bool isValid = string.IsNullOrWhiteSpace(overallComment);

            IEnumerable<string> keys = formCollection.AllKeys.Where(k => k.StartsWith("CriteriaID"));
            foreach (var key in keys)
            {
                string ratingID = formCollection[key];

                if (string.IsNullOrEmpty(ratingID))
                {
                    isValid = false;
                    continue;
                }

                string criteriaID = null;
                string criteriaComment = null;
                string studentID = null;

                //string value = formCollection[key];
                string[] parts = key.Split('=', '-');

                if (parts.Length >= 2)
                    criteriaID = parts[1];
                if (parts.Length == 4)
                    studentID = parts[3];

                if (!string.IsNullOrEmpty(formCollection[string.Format("Comment-{0}", key)]))
                {
                    criteriaComment = formCollection[string.Format("Comment-{0}", key)];
                }

                var evaluationDetail = new ProjectEvaluationDetail
                {
                    CriteriaID = int.Parse(criteriaID),
                    RatingID = int.Parse(ratingID),
                    Comments = criteriaComment,
                    StudentID = studentID
                };

                evaluationsDetails.Add(evaluationDetail);

                //Debug.WriteLine("ratingID {0},  criteriaID {1}, criteriaComment {2}, studentID {3}", ratingID, criteriaID, criteriaComment, studentID);
            }

            string facultyRole = formCollection["facultyRole"];
            bool oldIsNominatedByExaminer1 = bool.Parse(formCollection["oldIsNominatedByExaminer1"]);
            bool oldIsNominatedByExaminer2 = bool.Parse(formCollection["oldIsNominatedByExaminer2"]);

            if (facultyRole == "Examiner")
            {
                bool isNominatedByExaminer1 = (formCollection["IsNominatedByExaminer1"] != null ? true : false);
                if (isNominatedByExaminer1 != oldIsNominatedByExaminer1)
                    ProjectRepository.SetIsNominatedByExaminer1(projectID, isNominatedByExaminer1);
            }

            if (facultyRole == "SecondExaminer")
            {
                bool isNominatedByExaminer2 = (formCollection["IsNominatedByExaminer2"] != null ? true : false);
                if (isNominatedByExaminer2 != oldIsNominatedByExaminer2)
                    ProjectRepository.SetIsNominatedByExaminer2(projectID, isNominatedByExaminer2);
            }

            //if (!isValid)
            //{
            //    ModelState.AddModelError("", "You must complete all the evluation and provide an overall comment.");
            //    return View();
            //}

            GradingRepository.SaveProjectEvaluation(evaluationID, gradingType, projectID, facultyID, overallComment, evaluationsDetails);

            //UserInfo userInfo = Session["UserInfo"] as UserInfo;
            //ViewBag.CriteriaCategories = GradingRepository.GetCriteriaCategories(projectID, int.Parse(userInfo.UserID));
            //ViewBag.Ratings = GradingRepository.GetRatings();
            TempData["Message"] = string.Format("Grading for Project {0} was saved successfully.", projectID);
            TempData["ProjectID"] = projectID;
            return RedirectToAction("Index", "Home");
        }


        //[HttpGet]
        //public ActionResult GetProjectGrades(int projectID, string gradingType)
        //{

        //    var userInfo = GetUserInfo();
        //    int facultyID = (userInfo.IsFaculty ? int.Parse(userInfo.UserID) : 0);

        //    ProjectSummary projectSummary = ProjectRepository.GetProjectSummary(projectID, facultyID);

        //    ViewBag.ProjectSummary = projectSummary;

        //    var projectGrades = GradingRepository.GetProjectGrades(projectID, "0", gradingType);
        //    return PartialView(projectGrades);
        //}

        [HttpGet]
        [Authorize]
        public ActionResult ProjectGrades(int projectID, string gradingType, string role)
        {

            var userInfo = GetUserInfo();
            int facultyID = (userInfo.IsFaculty ? int.Parse(userInfo.UserID) : 0);

            ProjectSummary projectSummary = ProjectRepository.GetProjectSummary(projectID, facultyID);

            ViewBag.ProjectSummary = projectSummary;
            ViewBag.GradingType = gradingType;
            ViewBag.ExaminerRole = role;

            var projectGrades = GradingRepository.GetProjectGrades(projectID, "0", gradingType, role);
            return View(projectGrades);
        }

        [HttpGet]
        [Authorize]
        public ActionResult StudentGrades(int? projectID, string studentID, string gradingType, bool showSummaryOnly = false, string role = null)
        {

            if (gradingType == null)
                gradingType = "";

            if (string.IsNullOrEmpty(studentID))
            {
                var userInfo = GetUserInfo();
                if (userInfo.IsStudent)
                {
                    studentID = userInfo.UserID;
                    showSummaryOnly = true;
                }
                else
                {
                    ViewBag.ErrorMessage = "A student must be selected first.";
                    return View();
                }
            }

            if (projectID == null || projectID == 0)
            {
                //UserInfo userInfo = Session["UserInfo"] as UserInfo;
                //if (Request.IsAuthenticated && userInfo == null)
                //{
                //    //Store the User Info in a Session
                //    userInfo = UserRepository.GetUserInfo(User.Identity.Name);

                //    if (userInfo != null)
                //        Session["UserInfo"] = userInfo;
                //    else
                //        return RedirectToAction("LogOn", "Account");
                //}
                //studentID = userInfo.UserID;
                projectID = ProjectRepository.GetStudentProjectID(studentID);
                if (projectID == null || projectID.Value == 0)
                {
                    ViewBag.ErrorMessage = "You do not have a project.";
                    return View();
                }
            }

            ViewBag.Project = ProjectRepository.GetProject(projectID.Value);

            var projectSummary = ProjectRepository.GetProjectSummary(projectID.Value, 0);

            //projectSummary.Students = Regex.Replace(projectSummary.Students, @"\r\n", "<br/>", RegexOptions.Multiline);
            //projectSummary.Supervisors = Regex.Replace(projectSummary.Supervisors, @"\r\n", "<br/>", RegexOptions.Multiline);

            ViewBag.ProjectSummary = projectSummary;

            List<StudetGradeDetail> gradeDetails;
            if (showSummaryOnly)
                gradeDetails = GradingRepository.GetStudentGradeSummary(projectID.Value, studentID, gradingType);
            else
                gradeDetails = GradingRepository.GetStudentGradeDetails(projectID.Value, studentID, gradingType, role);

            foreach (var evaluationDetail in gradeDetails)
            {
                evaluationDetail.CriteriaDescription = Regex.Replace(evaluationDetail.CriteriaDescription, @"\r\n", "<br/>", RegexOptions.Multiline);
                evaluationDetail.Comments = Regex.Replace(evaluationDetail.Comments, @"\r\n", "<br/>", RegexOptions.Multiline);
                evaluationDetail.OverallComments = Regex.Replace(evaluationDetail.OverallComments, @"\r\n", "<br/>", RegexOptions.Multiline);
            }

            ViewBag.GradeDetails = gradeDetails;

            var projectGrades = GradingRepository.GetProjectGrades(projectID.Value, studentID, gradingType, role);
            return View(projectGrades);
        }


        [HttpGet]
        [Authorize]
        public ActionResult AllGrades()
        {
            var grades = GradingRepository.GetAllGrades();
            return View(grades);
        }
    }
}
